package com.zy.cloud.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName: MyLb
 * @Description: 自定义实现负载均衡算法--轮询算法
 * @Author: yanzy
 * @Date: 2021/3/3 11:52
 */
@Slf4j
@Component
public class MyLb implements MyLoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final Integer getAndIncrement() {
        int next;
        int current;
        // 使用自旋锁
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        log.info("当前第 {} 次访问.....", next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
